package lab3.nio;

import config.ATMData;
import config.Config;

import java.io.*;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerThroughPutNIO {
    /**
     * When client connected to server,
     * Server send objects to client.
     * Client calculate number of getting objects per second
     *
     * @param args
     */
    public static void main(String[] args) {
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
            serverSocketChannel.socket().bind(new InetSocketAddress(Config.PORT));
            System.out.println("Waiting for client on port " + serverSocketChannel.getLocalAddress() + "...");
            try (SocketChannel client = serverSocketChannel.accept()) {
                System.out.println("Just connected to " + client.getRemoteAddress());

                try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(client.socket().getOutputStream()))) {
                    while (true) {
                        ATMData atmData = ATMData.generate();
                        oos.writeObject(atmData);
                        oos.flush();
                        System.out.println("send: " + atmData);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
